package com.spider.silence.pool;

import com.google.common.collect.Lists;
import com.spider.silence.downloader.ChengduLifeDownLoader;
import com.spider.silence.utils.PropertiesUtil;
import org.apache.log4j.Logger;

import java.lang.reflect.InvocationTargetException;
import java.util.LinkedList;


/**
 * Created by qiuhao on 2017/1/11.
 */
public class ChengduLifeDownLoaderPool  {


    private Logger logger = Logger.getLogger(ChengduLifeDownLoaderPool.class);
  private static  ChengduLifeDownLoaderPool instance=new ChengduLifeDownLoaderPool();
    protected LinkedList<ChengduLifeDownLoader> pool = Lists.newLinkedList();
    private   ChengduLifeDownLoaderPool(){
        int initNum= Integer.parseInt(PropertiesUtil.getVal("ChengDuLife.DownLoader.Pool.initNum"));
        ChengduLifeDownLoader downLoader =new ChengduLifeDownLoader();
        downLoader.init();
        for(int i=0;i<initNum;i++){
            ChengduLifeDownLoader chengduLifeDownLoader = null;
            try {
                chengduLifeDownLoader =  downLoader.cloneDownLoader();
                pool.add(chengduLifeDownLoader);
            }  catch (NoSuchMethodException e) {
                e.printStackTrace();
                logger.error(e);
            } catch (InstantiationException e) {
                e.printStackTrace();
                logger.error(e);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
                logger.error(e);
            } catch (InvocationTargetException e) {
                logger.error(e);
                e.printStackTrace();
            }
        }
    }
    public  static  ChengduLifeDownLoaderPool getInstance(){
        return  instance;
    }
    public  void releaseDownLoader(ChengduLifeDownLoader downloader) {
        if (downloader != null) {
            synchronized (pool) {
                pool.addLast(downloader);
                pool.notifyAll();
            }
        }
    }
    public  ChengduLifeDownLoader fetchDownLoader(long mills) throws InterruptedException {
        synchronized (pool){
            if(mills<=0){
                while (pool.isEmpty()){
                    pool.wait();
                }
                return pool.removeFirst();
            }else {
                long future= System.currentTimeMillis()+mills;
                long remianing=mills;
                while (pool.isEmpty() && remianing >0){
                    pool.wait(remianing);
                    remianing=future-System.currentTimeMillis();
                }
                ChengduLifeDownLoader downLoader =null;
                if(!pool.isEmpty()){
                    downLoader=pool.removeFirst();
                }
                return downLoader;
            }
        }
    }
    /**
     * 清空池
     */
    public void empty(){
        pool=Lists.newLinkedList();
    }

}
